{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 线性回归的求解"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 介绍"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "本挑战需要你利用前面所学到的 PyTorch 知识，完成线性回归问题的求解。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 知识点"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 损失的定义\n",
    "- 优化器的定义\n",
    "- 模型的训练"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 线性回归的求解"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "首先，让我们来模拟一下，线性回归所需的数据集合："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[<matplotlib.lines.Line2D at 0x7fc7c8ca6310>]"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYQAAAD7CAYAAABqvuNzAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjMsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+AADFEAAAdcklEQVR4nO3df5Dc9X3f8eeuZJ1l3V0r3Z1ETBA/EvRu5IFWGE80Mhbt2DXTmRIaKU0lkMSZqJimjesJGcWTdPpP4zGDTWsclIqMbCQkIScMlLjuNJ7JTIIsrsoYY4YwTN5gEJJCEPdDtHcn4GTdbv+43WPvbr+73939/tjd7+sxwwh9P9rvfb6W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G3mVu2amn26v4mdm3gG3AFcA4MOHun0i3V/Ezs08ALwOvAu+XLp92919Nr1etU0AQERFAKSMRESlRQBAREUABQUREShQQREQEUEAQEZESBQQREQEUEEREpEQBQUREAPj/n7vyUKihDbYAAAAASUVORK5CYII=\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "import numpy as np\n",
    "from sklearn import datasets\n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline\n",
    "\n",
    "X_numpy, y_numpy = datasets.make_regression(\n",
    "    n_samples=100, n_features=1, noise=20, random_state=4)\n",
    "plt.plot(X_numpy, y_numpy, 'ro')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如上，我们初始化了一个数据集合。从图中可以看出，该数据集合大致上呈线性分布。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "本挑战的目的就寻找一个良好的函数表达式（又叫做模型），该函数表达式能够很好的描述上面数据点的分布，即对上面数据点进行拟合。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在使用 PyTorch 求解模型之前，我们需要将上面的数据集转为 PyTorch 认识的张量。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-info\">\n",
    "    <p><i class=\"fa fa-check-square\" aria-hidden=\"true\"> 挑战</i>：将 X_numpy，y_numpy 转为张量 。</p>\n",
    "    <p><i class=\"fa fa-plus-square\" aria-hidden=\"true\"> 要求</i> 转换后的张量用 X,y 表示。</p>\n",
    "    <p><i class=\"fa fa-plus-square\" aria-hidden=\"true\"> 提示</i> 需要利用 tensor.view() 将 y 的维度转 为 2 维。</p>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(torch.Size([100, 1]), torch.Size([100, 1]))"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "\n",
    "# 编写代码处\n",
    "X = torch.from_numpy(X_numpy)\n",
    "y = torch.from_numpy(y_numpy.reshape(100,1))\n",
    "# 转换数据类型为float32\n",
    "X = X.float()\n",
    "y = y.float()\n",
    "# 测试代码\n",
    "X.size(), y.size()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-warning\">\n",
    "<h4>重要说明</h4>\n",
    "<p>本课程中，Notebook 挑战系统无法自动评判，你需要自行补充上方单元格中缺失的代码并运行，如果输出结果和下方的期望输出结果一致，即代表此挑战顺利通过。完成全部内容后，点击「提交检测」即可通过，此说明后续不再出现。</p>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<i class=\"fa fa-sign-out\" aria-hidden=\"true\"> 期望输出</i>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`(torch.Size([100, 1]), torch.Size([100, 1]))`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "根据上面图像中数据点的分布情况，我们可以看出，该问题的解决模型应该是一个线性函数模型。接下来让我们使用 PyTorch 来初始化这个线性模型。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-info\">\n",
    "    <p><i class=\"fa fa-check-square\" aria-hidden=\"true\"> 挑战</i>：线性函数模型的定义 。</p>\n",
    "    <p><i class=\"fa fa-plus-square\" aria-hidden=\"true\"> 要求</i> ：用 model 变量表示线性函数模型。</p>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Linear(in_features=1, out_features=1, bias=True)"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 补充代码 ###\n",
    "model = nn.Linear(in_features=1,out_features=1,bias=True)\n",
    "# 测试代码\n",
    "model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<i class=\"fa fa-sign-out\" aria-hidden=\"true\"> 期望输出</i>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`Linear(in_features=1, out_features=1, bias=True)`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "定义完模型后，接下来，让我们来定义学习率、损失函数和优化器。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-info\">\n",
    "    <p><i class=\"fa fa-check-square\" aria-hidden=\"true\"> 挑战</i>：利用 PyTorch 定义学习率、损失函数和优化器 。</p>\n",
    "    <p><i class=\"fa fa-plus-square\" aria-hidden=\"true\"> 要求</i> ：损失采用均方差损失，学习率取 0.01 。</p>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "SGD (\n",
       "Parameter Group 0\n",
       "    dampening: 0\n",
       "    lr: 0.01\n",
       "    momentum: 0\n",
       "    nesterov: False\n",
       "    weight_decay: 0\n",
       ")"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "### 补充代码 ###\n",
    "learning_rate = 0.01\n",
    "loss = nn.MSELoss()\n",
    "optimizer  = torch.optim.SGD(params=model.parameters(), lr=learning_rate)\n",
    "# 测试代码\n",
    "optimizer"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<i class=\"fa fa-sign-out\" aria-hidden=\"true\"> 期望输出</i>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "    SGD (\n",
    "    Parameter Group 0\n",
    "        dampening: 0\n",
    "        lr: 0.01\n",
    "        momentum: 0\n",
    "        nesterov: False\n",
    "        weight_decay: 0\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "最后让我们进行模型的训练，即将数据传入模型中，然后利用梯度下降算法不断的迭代，找到最佳的模型。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-info\">\n",
    "    <p><i class=\"fa fa-check-square\" aria-hidden=\"true\"> 挑战</i>：利用 PyTorch 训练线性模型 。</p>\n",
    "    <p><i class=\"fa fa-plus-square\" aria-hidden=\"true\"> 提示</i> ：可以循环迭代 100 次左右 。</p>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 0, loss 5563.520\n",
      "epoch 2, loss 5174.758\n",
      "epoch 4, loss 4814.695\n",
      "epoch 6, loss 4481.208\n",
      "epoch 8, loss 4172.334\n",
      "epoch 10, loss 3886.254\n",
      "epoch 12, loss 3621.282\n",
      "epoch 14, loss 3375.859\n",
      "epoch 16, loss 3148.541\n",
      "epoch 18, loss 2937.992\n",
      "epoch 20, loss 2742.971\n",
      "epoch 22, loss 2562.332\n",
      "epoch 24, loss 2395.013\n",
      "epoch 26, loss 2240.031\n",
      "epoch 28, loss 2096.476\n",
      "epoch 30, loss 1963.501\n",
      "epoch 32, loss 1840.329\n",
      "epoch 34, loss 1726.234\n",
      "epoch 36, loss 1620.547\n",
      "epoch 38, loss 1522.648\n",
      "epoch 40, loss 1431.962\n",
      "epoch 42, loss 1347.957\n",
      "epoch 44, loss 1270.139\n",
      "epoch 46, loss 1198.054\n",
      "epoch 48, loss 1131.277\n",
      "epoch 50, loss 1069.418\n",
      "epoch 52, loss 1012.113\n",
      "epoch 54, loss 959.027\n",
      "epoch 56, loss 909.850\n",
      "epoch 58, loss 864.292\n",
      "epoch 60, loss 822.088\n",
      "epoch 62, loss 782.990\n",
      "epoch 64, loss 746.769\n",
      "epoch 66, loss 713.213\n",
      "epoch 68, loss 682.126\n",
      "epoch 70, loss 653.326\n",
      "epoch 72, loss 626.644\n",
      "epoch 74, loss 601.925\n",
      "epoch 76, loss 579.024\n",
      "epoch 78, loss 557.807\n",
      "epoch 80, loss 538.150\n",
      "epoch 82, loss 519.939\n",
      "epoch 84, loss 503.066\n",
      "epoch 86, loss 487.434\n",
      "epoch 88, loss 472.950\n",
      "epoch 90, loss 459.532\n",
      "epoch 92, loss 447.099\n",
      "epoch 94, loss 435.580\n",
      "epoch 96, loss 424.907\n",
      "epoch 98, loss 415.019\n"
     ]
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYQAAAD7CAYAAABqvuNzAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjMsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+AADFEAAAgAElEQVR4nO3de3RU5aH+8e9MQiISUskNqoJ4461YbaF6ilQBq9XVZamn0J6CIqXUWttlW1sRse1p1zpHj3hpay1a8CByFVqXVPzV3tY5VhAp9V71qK+i3IoCIaGGoASSmd8fmYmZzJ6ZPTN79p7JPJ+1XJh3z+x5N9H9zH6voWg0ioiISDjoCoiISHFQIIiICKBAEBGRGAWCiIgACgQREYmpDLoCeagGzgbeAboCrouISKmoAD4MPA109D5QyoFwNvBE0JUQESlR5wEbexeUciC8A7B//0EikeKbS1FfX0NLS3vQ1QhEuV57uV436NpL6drD4RBDhgyC2D20t1IOhC6ASCRalIEAFG29/FCu116u1w269hKU1NSuTmUREQEUCCIiEqNAEBERQIEgIiIxpdypLCJScto2b2Lf2ofobG2hsq6ehilTqR03PuhqAQoEERHftG3exJ7lS4kePgxAZ2sLe5YvBSiKUFCTkYiIT/atfagnDOKihw+zb+1DAdUokZ4QRER80tnaklW5k0I2OekJQUTEJ5V19VmV9xVvcooHSLzJqW3zJk/qp0AQEfFJw5SphKqqEspCVVU0TJnq6v2FbnJSk5GIiE/iT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7X2C8HVKn8KBBERAdRkJCIiMQoEEREBFAgiIhKjQBAREUCBICIiMQoEEREBFAgiIhKjQBAREQD+PwqtuDY0TlVwAAAAAElFTkSuQmCC\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "### 补充代码 ###\n",
    "epoches = 100\n",
    "for epoch in range(epoches):\n",
    "    # 前向传播\n",
    "    y_pred = model(X)\n",
    "    # 计算损失\n",
    "    loss_val = loss(y,y_pred)\n",
    "    # 反向传播\n",
    "    loss_val.backward()\n",
    "    # 更新梯度\n",
    "    optimizer.step()\n",
    "    # 梯度清零\n",
    "    optimizer.zero_grad()\n",
    "    # 打印训练情况\n",
    "    if epoch%2==0:\n",
    "        print(f'epoch {epoch:}, loss {loss_val:.3f}')\n",
    "\n",
    "\n",
    "# 测试代码：将通过模型预测出来的值展示到图像中\n",
    "# 预测结果并转为 NumPy 的形式\n",
    "predicted = model(X).detach().numpy()\n",
    "\n",
    "plt.plot(X_numpy, y_numpy, 'ro')\n",
    "plt.plot(X_numpy, predicted, 'b')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![image](https://doc.shiyanlou.com/courses/2534/1166617/7f9d58eda026aa1cbae103efc9e227b4-0/wm)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 参考答案"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "本挑战的参考答案如下，点击下拉框即可获取。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "        <summary>参考答案</summary>\n",
    "        <p>挑战 1 的参考答案</p>\n",
    "        <pre><code>X = torch.from_numpy(X_numpy.astype(np.float32))\n",
    "y = torch.from_numpy(y_numpy.astype(np.float32))\n",
    "y = y.view(y.shape[0], 1)</code></pre>\n",
    "       <p>挑战 2 的参考答案</p>\n",
    "        <pre><code>n_samples, n_features = X.shape\n",
    "input_size = n_features\n",
    "output_size = 1\n",
    "model = nn.Linear(input_size, output_size)\n",
    "</code></pre>\n",
    "           <p>挑战 3 的参考答案</p>\n",
    "        <pre><code>learning_rate = 0.01\n",
    "criterion = nn.MSELoss()\n",
    "optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate) \n",
    "</code></pre>\n",
    "           <p>挑战 4 的参考答案</p>\n",
    "        <pre><code>num_epochs = 100\n",
    "for epoch in range(num_epochs):\n",
    "    # Forward pass and loss\n",
    "    y_predicted = model(X)\n",
    "    loss = criterion(y_predicted, y) \n",
    "    # Backward pass and update\n",
    "    loss.backward()\n",
    "    optimizer.step()\n",
    "    # zero grad before new step\n",
    "    optimizer.zero_grad()\n",
    "    if (epoch+1) % 10 == 0:\n",
    "        print(f'epoch: {epoch+1}, loss = {loss.item():.4f}')\n",
    "</code></pre>\n",
    "</details>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 实验总结"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "通过对线性问题的求解，我想你已经了解了如何利用 PyTorch 训练模型的整个过程。当然，本次挑战只是利用梯度下降算法进行了简单的线性回归。在下一个实验中，我们会尝试使用该算法进行非线性问题的求解。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<hr><div style=\"color: #999; font-size: 12px;\"><i class=\"fa fa-copyright\" aria-hidden=\"true\"> 本课程内容版权归蓝桥云课所有，禁止转载、下载及非法传播。</i></div>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
